#define _CRT_SECURE_NO_WARNINGS
#include"Queue.h"

void QueueInit(Queue* q)
{
	assert(q);
	q->head = NULL;
	q->tail = NULL;
	q->size = 0;
}

int QueueEmpty(Queue* q)
{
	assert(q);
	return q->head == NULL;
}

void QueuePush(Queue* q, QDataType data)
{
	assert(q);
	QNode* newnode = (QNode*)malloc(sizeof(QNode));
	if (!newnode)
	{
		perror("malloc");
		exit(1);
	}
	newnode->data = data;
	newnode->next = NULL;
	if (!QueueEmpty(q))
	{
		q->tail->next = newnode;
		q->tail = q->tail->next;
	}
	else
		q->tail = q->head = newnode;
	q->size++;
}

void QueuePop(Queue* q)
{
	assert(q);
	assert(!QueueEmpty(q));
	QNode* next = q->head->next;
	free(q->head);
	if (q->size == 1)
		q->tail = NULL;
	q->head = next;
	q->size--;
}

QDataType QueueFront(Queue* q)
{
	assert(q);
	assert(!QueueEmpty(q));
	return q->head->data;
}

QDataType QueueBack(Queue* q)
{
	assert(q);
	assert(!QueueEmpty(q));
	return q->tail->data;
}

int QueueSize(Queue* q)
{
	assert(q);
	return q->size;
}

void QueueDestroy(Queue* q)
{
	assert(q);
	assert(!QueueEmpty(q));
	QNode* pcur = q->head;
	while (pcur)
	{
		QNode* next = pcur->next;
		free(pcur);
		pcur = next;
		q->size--;
	}
	q->head = q->tail = NULL;
	q->size = 0;
}
